package com.example.springbootweb.controller;

import com.example.springbootweb.dao.DepartmentDao;
import com.example.springbootweb.dao.EmployeeDao;
import com.example.springbootweb.entities.Department;
import com.example.springbootweb.entities.Employee;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

@Controller
public class EmployeeController {
    @Autowired
    EmployeeDao employeeDao;
    @Autowired
    DepartmentDao departmentDao;
    //查询所有员工返回列表页面
    @GetMapping(value = "/emps")
    public String list(Model model){
       Collection<Employee> employees = employeeDao.getAll();

       //放在请求域中
        model.addAttribute("emps",employees);

        //thymeleaf默认会拼串
       return "emp/list";
    }

    //来到添加页面
    @GetMapping("/emp")
    public String toAddPage(Model model){
        //查出所有的部门,在页面显示
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("departments",departments);
        return "emp/add";
    }

    //员工添加
    //springmvc自动将请求参数自动封装
    @PostMapping("/emp")
    public String addEmp(Employee employee){

        /*Logger logger = LoggerFactory.getLogger(EmployeeController.class);
        logger.error(employee.toString());*/
        System.out.println(employee);
        employeeDao.save(employee);
        //回到员工列表页面
        //redirect: 表示重定向
        //forward: 表示转发
        return "redirect:/emps";
    }

    //来到修改页面，查到当前员工，进行回显
    @GetMapping("/emp/{id}")
    public String toEditPage(@PathVariable("id") Integer id,Model model){
        Employee employee = employeeDao.get(id);
        model.addAttribute("emp",employee);

        //查出所有的部门,在页面显示
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("departments",departments);

        System.out.println(employee);
        return "emp/add";
    }

    //修改员工数据
    @PutMapping("/emp")
    public String tomodifyPage(Employee employee){
        //需要提交员工的ID
        employeeDao.save(employee);
        System.out.println(employee);
        return "redirect:/emps";
    }

    @DeleteMapping("/emp/{id}")
    public String todeletePage(@PathVariable("id") Integer id){
        System.out.println(id);
        employeeDao.delete(id);
        return "redirect:/emps";
    }
}
